package mlz.j_proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/*
    代理对象 ->  完成复用性
 */
public class ProxyUtil {
    public static UserService createProxyService(UserService userService){
        UserService userServiceProxy = (UserService) Proxy.newProxyInstance(
                ProxyUtil.class.getClassLoader(),
                new Class[]{UserService.class},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        if (method.getName().equals("login") ||
                                method.getName().equals("deleteUsers")  ||
                                method.getName().equals("selectUsers") ){
                            long time1 = System.currentTimeMillis();

                            //对方法中的原始内容做引入操作
                            Object rs = method.invoke(userService, args);

                            long time2 = System.currentTimeMillis();
                            System.out.println(method.getName() + "方法耗时："+(time2-time1));

                            return rs;
                        }else {
                            Object rs = method.invoke(userService, args);
                            return rs;
                        }

                    }
                }
        );

        return userServiceProxy;
    }

}
























